<template>

  <body>
    <div class="news-box" v-if="selectedParentColumn && selectedParentColumn.name === '馆院简讯'">
      <div class="news-box-content">
        <p class="news-box-content-title">{{ selectedParentColumn.name }}</p>
        <div class="news-box-content-detail">
          <!-- 渲染子栏目列表 -->
          <div class="news-box-content-tab">
            <div class="news-box-content-tab-box">
              <div v-for="(child, index) in childrenColumns" :key="index"
                class="news-box-content-tab-item news-tab-item"
                :class="{ active: selectedChildColumnId === child.columnId, selected: selectedChildColumnId === child.columnId }"
                @click="fetchArticleList(child.columnId)">
                <div>{{ child.name }}<span class="iconfont icon-jiantou_xiangyou_o news-item-icon"></span></div>
              </div>
            </div>
          </div>

          <div class="news-box-content-tab-page active">

            <!-- 文章列表渲染区域 -->
            <div v-if="articleList.length" class="news-article-list">
              <div v-for="article in articleList.slice(0, 6)" :key="article.articleId" class="news-article-item">
                <div class="news-article-date">{{ formatDate(article.createdTime) }}</div>
                <div class="news-article-content">
                  <h2>{{ article.title }}</h2>
                  <p>{{ article.resume }}</p>
                </div>
              </div>
            </div>
            <p v-else-if="loading">加载中...</p>
            <p v-else>没有文章。</p>

            <a v-if="selectedParentColumn.moreLink" class="news-more" target="_blank"
              :href="selectedParentColumn.moreLink">查看更多</a>
          </div>
        </div>
      </div>
    </div>

  </body>
</template>

<script>
// 导入JavaScript文件
import '../assets/js/public/jquery.js';
import '../assets/js/public/translate.js';
import '../assets/js/public/reset.js';

import { defineComponent, computed, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useColumnsStore } from '@/store/column';

import { getArticleListService } from '@/api/user.js';


export default defineComponent({
  name: 'news',
  components: {

  },
  setup() {
    const columnsStore = useColumnsStore();
    const router = useRouter();
    const route = useRoute();

    // 根据路由参数加载专栏数据（如果有的话）
    if (route.params.id) {
      console.log('当前专栏ID:', route.params.id);
      // 根据专栏ID加载数据等逻辑
    }

    // 导航到栏目详情页的方法
    const navigateToColumn = (columnId) => {
      columnsStore.selectColumn(columnId);
      router.push({ path: `/column/${columnId}` });
    };

    // 将parentColumns分组为两个数组，每个包含最多6个元素
    const groupedColumns = computed(() => {
      return [
        parentColumns.value.slice(0, 6),
        parentColumns.value.slice(6, 12)
      ].filter(group => group.length > 0);
    });

    const parentColumns = computed(() => columnsStore.parentColumns);
    // 计算属性用于获取当前选中的父栏目和其子栏目
    const selectedParentColumn = computed(() => columnsStore.selectedParentColumn);
    const childrenColumns = computed(() => columnsStore.childrenColumns);

    const articleList = ref([]); // 文章列表
    const loading = ref(false);  // 加载状态
    const selectedChildColumnId = ref(null); // 当前选中的子栏目ID

    // 获取文章列表的方法
    const fetchArticleList = async (childColumnId) => {
      console.log('馆院简讯当前选中的子专栏id是：', childColumnId);
      selectedChildColumnId.value = childColumnId; // 更新当前选中的子栏目ID
      articleList.value = []; // 清空之前的文章列表
      loading.value = true;
      try {
        const response = await getArticleListService({
          subColumnId: childColumnId, // 确保这里传递的是子栏目ID
          parentColumnId: selectedParentColumn.value.columnId, // 如果需要的话也传递父栏目ID
          state: '已发布' // 根据需求设置状态参数
        });
        articleList.value = response.data || response.data; // 响应数据包含在data属性中
      } catch (error) {
        console.error('Failed to fetch articles:', error);
      } finally {
        loading.value = false;
      }
    };
    const formatDate = (dateString) => {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
      return new Date(dateString).toLocaleDateString(undefined, options);
    };

    // 在组件挂载时获取父级栏目数据，并尝试加载默认的子栏目文章（如果有）
    onMounted(async () => {
      await columnsStore.fetchParentColumns();

      const newsColumn = columnsStore.parentColumns.find(column => column.name === '馆院简讯');
      if (newsColumn) {
        await columnsStore.fetchChildrenColumns(newsColumn.columnId);
        columnsStore.selectParentColumn(newsColumn);
        if (columnsStore.childrenColumns.length > 0) {
          selectedChildColumnId.value = columnsStore.childrenColumns[0].columnId;
          await fetchArticleList(selectedChildColumnId.value); // 确保这里调用了fetchArticleList
        }
      }
    });

    return {
      parentColumns,
      groupedColumns,
      navigateToColumn,
      selectedParentColumn,
      childrenColumns,
      articleList,
      loading,
      fetchArticleList,
      selectedChildColumnId,
      formatDate,
    };
  }
});

</script>

<style lang="scss">
@import '../assets/css/main/news-box.css';
</style>